package com.baizhou.honglv.service.impl;

import com.baizhou.honglv.bean.exception.SysException;
import com.baizhou.honglv.bean.util.ExcelUtil;
import com.baizhou.honglv.entity.Excel;
import com.baizhou.honglv.mapper.UserMapper;
import com.baizhou.honglv.service.BackService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.util.List;

/**
 * @author HaiPeng Wang
 * @date 2021/7/17 18:19
 * @Description:
 */
@Service
public class BackServiceImpl implements BackService {

    @Autowired
    UserMapper userMapper;
    /**
     * 用于实现文件的上传数据逻辑功能
     *
     * @param file
     * @return
     */
    @Override
    public void uploadFile(CommonsMultipartFile file, String uploadPath, InputStream inputStream) {
        //获取文件名，含带文件后缀名
        String uploadFileName = file.getOriginalFilename();
        if (uploadFileName == null || uploadFileName.equals("")){
            throw new SysException("上传文件失败！");
        }
        File realFile = new File(uploadPath);
        System.out.println(uploadPath);
        if (!realFile.exists()){
            realFile.mkdir();
        }
        try (
                InputStream is = file.getInputStream();
                OutputStream os = new FileOutputStream(new File(realFile,uploadFileName))
                ){
            int len;
            byte[] bytes = new byte[1024];
            while ((len = is.read(bytes)) != -1){
                os.write(bytes,0,len);
                os.flush();
            }
            System.out.println(file.getOriginalFilename()+"2");
            List<Excel> list = ExcelUtil.readExcelToEntity(Excel.class,file.getInputStream(),uploadFileName);
            for (Excel excel: list){
//                User user = new User(excel.getStudentName(),excel.getDirection(),excel.getPeriod());
//                userMapper.insert(user);
            }

        }catch (Exception e){
            throw new SysException("上传失败！");
        }

    }
}
